package com.yc.spring.aop;

import com.yc.cinema.biz.BizException;
import com.yc.cinema.biz.UserBiz;
import com.yc.spring.bbs.dao.UserDao;
import com.yc.spring.bbs.dao.UserDaoImpl;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;


//CGLIB  动态字节码   基于继承方式，不要求代理类实现接口
public class CglibProxy {
    public static  Object proxy(Object target){
        Enhancer enhancer = new Enhancer();
        //设置父类
        enhancer.setSuperclass(target.getClass());
        //方法拦截器(回调)
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            /**
             * 代理对象
             * 方法
             * 参数
             * 代理方法
             */
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                Object ret = methodProxy.invoke(target,objects);
                System.out.println("后置拦截  " + method);
                return ret;
            }
        });
        //创建代理对象
        return enhancer.create();
    }


    public static void main(String[] args) throws BizException {
        UserDao userDao = new UserDaoImpl();
        UserDao userDaoProxy = (UserDao) proxy(userDao);
        userDaoProxy.insert(null);

        UserBiz userBiz = new UserBiz();
        UserBiz userBizProxy = (UserBiz)proxy(userBiz);
        userBizProxy.register(null);


    }
}
